// TODO:
function formatQuery(url) {
  return url;
}

// TODO:
function formatData(data) {
  return (data && JSON.stringify(data)) || null;
}

function responseTextHandle(res) {
  try {
    const jsonData = JSON.parse(res);
    // TODO 强制返回code 0
    jsonData.code = 0;
    jsonData.errcode = 0;
    return jsonData;
  } catch (e) {
    return res;
  }
}

export function request(url, query, data, options) {
  const xhr = new XMLHttpRequest();
  const { method, rurl, async = false } = options;
  xhr.open(method, formatQuery(url, query), async); //使用同步请求
  xhr.setRequestHeader('content-type', 'application/json');
  xhr.send(data);

  if (async) {
    const p = new Promise((resolve, reject) => {
      xhr.onreadystatechange = () => {
        if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          resolve(responseTextHandle(xhr.responseText));
        } else {
          reject(xhr.responseText);
        }
      };
      xhr.onerror = e => {
        console.log(`%c [Mock Api Proxy Error ${rurl} To >>> ${url} ]`, 'color:#f56c6c', '\n', e);
        reject(e);
      };
    });
    return p;
  }

  return responseTextHandle(xhr.responseText);
}

export function get(url, params, options = {}) {
  return request(url, params, formatData(options.data), {
    ...options,
    method: 'GET',
  });
}

export function post(url, data, options = {}) {
  return request(url, options.query, formatData(data), {
    ...options,
    method: 'POST',
  });
}
